/*  LocationViewer.java - Activity to show detected locationss 
 
        Copyright (C) 2009 Devendra Laulkar

        This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation version 2 of the License. 

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package com.intellBatt;

import java.util.Date;
import java.util.HashMap;

import com.intellBatt.services.MLService;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class LocationViewer extends ListActivity {

	private LocationDbAdapter dbhelper;
	//private LocationModel model;
	private boolean registered;

	/* GUI Constants and elements */
	public static final int MENU_ADD = 0;
	public static final int MENU_MYLOCATION = 1;
	public static final int MENU_STOP = 2;

	private HashMap<String, LocationModel> locations; 

	/** Called when the activity is first created. */

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location_list);

		dbhelper = new LocationDbAdapter(this);
		dbhelper.open();

		locations = new HashMap<String, LocationModel>();
		loadModels();
		setGui();
		setTitle(getString(R.string.locationsTitle));
		//startService(new Intent("com.microlocation.services.BATT"));
	}

	/* End of onCreate() */

	public void onPause()
	{
		super.onPause();
	}

	public void onStop()
	{
		super.onStop();
	}

	public void onDestroy()
	{
		dbhelper.close();
		super.onDestroy();
	}

	private void loadModels() {
		Cursor c = dbhelper.fetchAllLocations();

		if(c == null || c.getCount() == 0)
		{
			return;
		}

		c.moveToFirst();
		int idCol = c.getColumnIndex(LocationDbAdapter.KEY_ROWID);
		int nameCol = c.getColumnIndex(LocationDbAdapter.KEY_LOCATION_NAME);
		int lastSeen = c.getColumnIndex(LocationDbAdapter.KEY_LASTUSE);
		int cnt = c.getColumnIndex(LocationDbAdapter.KEY_NUMLOCATED);

		do
		{
			long id = c.getLong(idCol);
			String name = c.getString(nameCol);
			String time = c.getString(lastSeen);
			


			LocationModel model = loadModelFromDb(id);
			Date d = new Date(Long.parseLong(time));
			
			model.setCount(c.getInt(cnt));
			model.setLastSeen(d);
			model.setLocationName(name);
			model.setId(id);
			
			locations.put(name, model );

		}while(c.moveToNext());

		//c.moveToFirst();
		c.close();
	}

	private LocationModel loadModelFromDb(long id) {

		Cursor c = dbhelper.fetchLocationModel(id);
		LocationModel t = new LocationModel();
		
		if(c == null || c.getCount() == 0)
		{
			Toast.makeText(this, "No entries for this location " + id,
					Toast.LENGTH_SHORT).show();
			dbhelper.deleteLocation(id);
			if(c != null)
			{
				c.close();
			}
			return t;
		}

		c.moveToFirst();
		int bssidCol = c.getColumnIndex(LocationDbAdapter.KEY_BSSID);
		int avgCol = c.getColumnIndex(LocationDbAdapter.KEY_AVG_VALUE);
		int maxCol = c.getColumnIndex(LocationDbAdapter.KEY_MAX_VALUE);
		int minCol = c.getColumnIndex(LocationDbAdapter.KEY_MIN_VALUE);
		int conn = c.getColumnIndex(LocationDbAdapter.KEY_CONNECTED);

		do
		{
			WifiNetwork w = new WifiNetwork(c.getString(bssidCol));

			w.setAverageVal(c.getDouble(avgCol));
			w.setMaxValue(c.getInt(maxCol));
			w.setMinValue(c.getInt(minCol));
			w.setConnected(c.getInt(conn));

			t.addNetwork(w);
		}while(c.moveToNext());
		c.close();
		return t;
	}

	private void setGui() 
	{
		Cursor c = dbhelper.fetchAllLocations();

		if(c == null || c.getCount() == 0)
		{
			return;
		}

		startManagingCursor(c);

		// Create an array to specify the fields we want to display in the list (only TITLE)
		String[] from = new String[]{LocationDbAdapter.KEY_LOCATION_NAME};

		// and an array of the fields we want to bind those fields to (in this case just text1)
		int[] to = new int[]{R.id.text1};

		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter notes = 
			new SimpleCursorAdapter(this, R.layout.location_row, c, from, to);
		setListAdapter(notes);
		//c.close();
	}


	public boolean onCreateOptionsMenu(Menu menu) 
	{
		super.onCreateOptionsMenu(menu);
		MenuItem item;
		//		item = menu.add(0, MENU_ADD,0, R.string.menuAdd);
		//		item.setIcon(android.R.drawable.ic_menu_add);
		//
		//		item = menu.add(0, MENU_MYLOCATION,0, R.string.menuLocation);
		//		item.setIcon(android.R.drawable.ic_menu_mylocation);
		//
		//		item = menu.add(0, MENU_STOP,0, R.string.menuStop);
		//		item.setIcon(android.R.drawable.ic_menu_revert);

		return true;
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {

		LocationModel model;

		super.onListItemClick(l, v, position, id);

		//model = (LocationModel) getListView().getItemAtPosition(position);
		
		
		TextView tv = (TextView)v.findViewById(R.id.text1);
		
		if(tv == null)
		{
			return;
		}
		
		model = locations.get(tv.getText());
		
		if(model == null)
		{
			return;
		}
		
		Intent mIntent = new Intent(this, LocationView.class);
		Bundle extras = new Bundle();
		extras.putLong(MLService.KEY_ID, model.getId());
		extras.putString(MLService.KEY_NAME, tv.getText().toString());
		extras.putInt(MLService.KEY_COUNT, model.getCount());
		extras.putLong(MLService.KEY_LASTSEEN, model.getLastSeen().getTime());
		mIntent.putExtras(extras);
		startActivity(mIntent);
		
	}
	public boolean onMenuItemSelected(int featureId, MenuItem item) 
	{
		super.onMenuItemSelected(featureId, item);
		
		switch(item.getItemId()) {

		}

		return true;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
		super.onActivityResult(requestCode, resultCode, intent);
	}



}